package com.gdth.log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.PowerManager.WakeLock;
import android.util.Log;

public class LogServer {
	private static final String TAG = "LogService";
	
	private static final int MEMORY_LOG_FILE_MAX_SIZE = 10 * 1024 * 1024; // 内存中日志文件最大值，10M
    private static final int MEMORY_LOG_FILE_MONITOR_INTERVAL = 10 * 60 * 1000; // 内存中的日志文件大小监控时间间隔，10分钟
    private static final int SDCARD_LOG_FILE_SAVE_DAYS = 7; // sd卡中日志文件的最多保存天数

    private String LOG_PATH_MEMORY_DIR; // 日志文件在内存中的路径(日志文件在安装目录中的路径)
    private String LOG_PATH_SDCARD_DIR; // 日志文件在sdcard中的路径
    @SuppressWarnings("unused")
    private String LOG_SERVICE_LOG_PATH; // 本服务产生的日志，记录日志服务开启失败信息

    public final int SDCARD_TYPE = 0; // 当前的日志记录类型为存储在SD卡下面
    public final int MEMORY_TYPE = 1; // 当前的日志记录类型为存储在内存中
    public int CURR_LOG_TYPE = SDCARD_TYPE; // 当前的日志记录类型

    private String CURR_INSTALL_LOG_NAME; // 如果当前的日志写在内存中，记录当前的日志文件名称

    private SimpleDateFormat myLogSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private OutputStreamWriter writer;

    private WakeLock wakeLock;
    private Context mContext;
    private Process process;
    AlarmManager am;
    
    /*
     * 是否正在监测日志文件大小； 如果当前日志记录在SDcard中则为false 如果当前日志记录在内存中则为true
     */
    private boolean logSizeMoniting = false;

    public static String MONITOR_LOG_SIZE_ACTION = "MONITOR_LOG_SIZE"; // 日志文件监测action
    public static String SWITCH_LOG_FILE_ACTION = "SWITCH_LOG_FILE_ACTION"; // 切换日志文件action

    public LogServer(WakeLock wakeLock, Context mContext){
    	this.wakeLock = wakeLock;
    	this.mContext = mContext;
    	setAlarmManager();
    	init();

    	this.deploySwitchLogFileTask();
        new LogCollectorThread(wakeLock, this).start();
    }
    
    private void init() {
        LOG_PATH_MEMORY_DIR = mContext.getFilesDir().getAbsolutePath() +
                File.separator
                + "Wonders"
                + File.separator
                + "log";
        LOG_SERVICE_LOG_PATH = LOG_PATH_MEMORY_DIR + File.separator
                + LogUtil.logServiceLogName;
        LOG_PATH_SDCARD_DIR = Environment.getExternalStorageDirectory()
                .getAbsolutePath()
                + File.separator
                + "Wonders"
                + File.separator
                + "log";
        createLogDir();

        

        CURR_LOG_TYPE = getCurrLogType();
        Log.i(TAG, "LogService onCreate");
    }

    /**
     * 检查日志文件大小是否超过了规定大小 如果超过了重新开启一个日志收集进程
     */
    public void checkLogSize() {
        if (CURR_INSTALL_LOG_NAME != null && !"".equals(CURR_INSTALL_LOG_NAME)) {
            String path = LOG_PATH_MEMORY_DIR + File.separator
                    + CURR_INSTALL_LOG_NAME;
            File file = new File(path);
            if (!file.exists()) {
                return;
            }
            Log.d(TAG, "checkLog() ==> The size of the log is too big?");
            if (file.length() >= MEMORY_LOG_FILE_MAX_SIZE) {
                Log.d(TAG, "The log's size is too big!");
                new LogCollectorThread(wakeLock, this).start();
            }
        }
    }

    /**
     * 创建日志目录
     */
    private void createLogDir() {
        File file = new File(LOG_PATH_MEMORY_DIR);
        boolean mkOk;
        if (!file.isDirectory()) {
            mkOk = file.mkdirs();
            if (!mkOk) {
                mkOk = file.mkdirs();
            }
        }

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            file = new File(LOG_PATH_SDCARD_DIR);
            if (!file.isDirectory()) {
                mkOk = file.mkdirs();
                if (!mkOk) {
                    recordLogServiceLog("move file failed,dir is not created succ");
                    return;
                }
            }
        }
    }
    

    /**
     * 根据当前的存储位置得到日志的绝对存储路径
     * 
     * @return
     */
    public String getLogPath() {
        createLogDir();
        String logFileName = LogUtil.sdf.format(new Date()) + ".log";// 日志文件名称
        if (CURR_LOG_TYPE == MEMORY_TYPE) {
            CURR_INSTALL_LOG_NAME = logFileName;
            Log.d(TAG, "Log stored in memory, the path is:"
                    + LOG_PATH_MEMORY_DIR + File.separator + logFileName);
            return LOG_PATH_MEMORY_DIR + File.separator + logFileName;
        } else {
            CURR_INSTALL_LOG_NAME = null;
            Log.d(TAG, "Log stored in SDcard, the path is:"
                    + LOG_PATH_SDCARD_DIR + File.separator + logFileName);
            return LOG_PATH_SDCARD_DIR + File.separator + logFileName;
        }
    }

    /**
     * 处理日志文件 1.如果日志文件存储位置切换到内存中，删除除了正在写的日志文件 并且部署日志大小监控任务，控制日志大小不超过规定值
     * 2.如果日志文件存储位置切换到SDCard中，删除7天之前的日志，移 动所有存储在内存中的日志到SDCard中，并将之前部署的日志大小 监控取消
     */
    public void handleLog() {
        if (CURR_LOG_TYPE == MEMORY_TYPE) {
            deployLogSizeMonitorTask();
            deleteMemoryExpiredLog();
        } else {
            moveLogfile();
            cancelLogSizeMonitorTask();
            deleteSDcardExpiredLog();
        }
    }

    /**
     * 部署日志大小监控任务
     */
    private void deployLogSizeMonitorTask() {
        if (logSizeMoniting) { // 如果当前正在监控着，则不需要继续部署
            return;
        }
        logSizeMoniting = true;
        Intent intent = new Intent(MONITOR_LOG_SIZE_ACTION);
        PendingIntent sender = PendingIntent.getBroadcast(this.mContext, 0, intent, 0);
        
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                MEMORY_LOG_FILE_MONITOR_INTERVAL, sender);
        Log.d(TAG, "deployLogSizeMonitorTask() succ !");
    }
    
    private void setAlarmManager(){
    	this.am = (AlarmManager) this.mContext.getSystemService(this.mContext.ALARM_SERVICE);
    }

    /**
     * 取消部署日志大小监控任务
     */
    private void cancelLogSizeMonitorTask() {
        logSizeMoniting = false;
        Intent intent = new Intent(MONITOR_LOG_SIZE_ACTION);
        PendingIntent sender = PendingIntent.getBroadcast(this.mContext, 0, intent, 0);
        am.cancel(sender);

        Log.d(TAG, "canelLogSizeMonitorTask() succ");
    }

    /**
     * 将日志文件转移到SD卡下面
     */
    private void moveLogfile() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        
        File file = new File(LOG_PATH_SDCARD_DIR);
        if (!file.isDirectory()) {
            boolean mkOk = file.mkdirs();
            if (!mkOk) {
                return;
            }
        }

        file = new File(LOG_PATH_MEMORY_DIR);
        if (file.isDirectory()) {
            File[] allFiles = file.listFiles();
            for (File logFile : allFiles) {
                String fileName = logFile.getName();
                if (LogUtil.logServiceLogName.equals(fileName)) {
                    continue;
                }

                boolean isSucc = copy(logFile, new File(LOG_PATH_SDCARD_DIR
                        + File.separator + fileName));
                if (isSucc) {
                    logFile.delete();
                }
            }
        }
    }

    /**
     * 删除内存下过期的日志
     */
    private void deleteSDcardExpiredLog() {
        File file = new File(LOG_PATH_SDCARD_DIR);
        if (file.isDirectory()) {
            File[] allFiles = file.listFiles();
            for (File logFile : allFiles) {
                String fileName = logFile.getName();
                if (LogUtil.logServiceLogName.equals(fileName)) {
                    continue;
                }
                String createDateInfo = LogUtil.getFileNameWithoutExtension(fileName);
                if (canDeleteSDLog(createDateInfo)) {
                    logFile.delete();
                    Log.d(TAG, "delete expired log success,the log path is:" + logFile.getAbsolutePath());
                }
            }
        }
    }

    /**
     * 判断sdcard上的日志文件是否可以删除
     * @param createDateStr
     * @return
     */
    public boolean canDeleteSDLog(String createDateStr) {
        boolean canDel = false;
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1 * SDCARD_LOG_FILE_SAVE_DAYS);// 删除7天之前日志
        Date expiredDate = calendar.getTime();
        try {
            Date createDate = LogUtil.sdf.parse(createDateStr);
            canDel = createDate.before(expiredDate);
        } catch (ParseException e) {
           // Log.e(TAG, e.getMessage(), e);
            canDel = false;
        }
        return canDel;
    }

    /**
     * 删除内存中的过期日志，删除规则： 除了当前的日志和离当前时间最近的日志保存其他的都删除
     */
    private void deleteMemoryExpiredLog() {
        File file = new File(LOG_PATH_MEMORY_DIR);
        if (file.isDirectory()) {
            File[] allFiles = file.listFiles();
            Arrays.sort(allFiles, new FileComparator());
            for (int i = 0; i < allFiles.length - 2; i++) { // "-2"保存最近的两个日志文件
                File _file = allFiles[i];
                if (LogUtil.logServiceLogName.equals(_file.getName())
                        || _file.getName().equals(CURR_INSTALL_LOG_NAME)) {
                    continue;
                }
                _file.delete();
                Log.d(TAG, "delete expired log success,the log path is:"
                        + _file.getAbsolutePath());
            }
        }
    }

    /**
     * 拷贝文件
     * 
     * @param source
     * @param target
     * @return
     */
    private boolean copy(File source, File target) {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            if (!target.exists()) {
                boolean createSucc = target.createNewFile();
                if (!createSucc) {
                    return false;
                }
            }
            in = new FileInputStream(source);
            out = new FileOutputStream(target);
            byte[] buffer = new byte[8 * 1024];
            int count;
            while ((count = in.read(buffer)) != -1) {
                out.write(buffer, 0, count);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //Log.e(TAG, e.getMessage(), e);
            recordLogServiceLog("copy file fail");
            return false;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
               // Log.e(TAG, e.getMessage(), e);
                recordLogServiceLog("copy file fail");
                return false;
            }
        }

    }
	
	/**
     * 记录日志服务的基本信息 防止日志服务有错，在LogCat日志中无法查找 此日志名称为Log.log
     * @param msg
     */
    public void recordLogServiceLog(String msg) {
        if (writer != null) {
            try {
                Date time = new Date();
                writer.write(myLogSdf.format(time) + " : " + msg);
                writer.write("\n");
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
               // Log.e(TAG, e.getMessage(), e);
            }
        }
    }
    

    /**
     * 获取当前应存储在内存中还是存储在SDCard中
     * 
     * @return
     */
    public int getCurrLogType() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return MEMORY_TYPE;
        } else {
            return SDCARD_TYPE;
        }
    }

    /**
     * 部署日志切换任务，每天凌晨切换日志文件
     */
    public void deploySwitchLogFileTask() {
        Intent intent = new Intent(SWITCH_LOG_FILE_ACTION);
        PendingIntent sender = PendingIntent.getBroadcast(this.mContext, 0, intent, 0);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        // 部署任务
        am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, sender);
        recordLogServiceLog("deployNextTask succ,next task time is:"
                + myLogSdf.format(calendar.getTime()));
    }

    /**
     * 开始收集日志信息
     */
    public void createLogCollector() {
        String logFileName = LogUtil.sdf.format(new Date()) + ".log";// 日志文件名称
        List<String> commandList = new ArrayList<String>();
        commandList.add("logcat");
        commandList.add("-f");
        // commandList.add(LOG_PATH_INSTALL_DIR + File.separator + logFileName);
        commandList.add(getLogPath());
        commandList.add("-v");
        commandList.add("time");
        commandList.add("*:I");

        // commandList.add("*:E");// 过滤所有的错误信息

        // 过滤指定TAG的信息
        // commandList.add("MyAPP:V");
        // commandList.add("*:S");
        try {
        	process = Runtime.getRuntime().exec(
                    commandList.toArray(new String[commandList.size()]));
            recordLogServiceLog("start collecting the log,and log name is:"
                    + logFileName);
            // process.waitFor();
        } catch (Exception e) {
            Log.e(TAG, "CollectorThread == >" + e.getMessage(), e);
            recordLogServiceLog("CollectorThread == >" + e.getMessage());
        }
    }
    
    public void onDestroy(){
    	 if (writer != null) {
             try {
                 writer.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }
         }
         if (process != null) {
             process.destroy();
         }
    }

    /**
     * 关闭由本程序开启的logcat进程： 根据用户名称杀死进程(如果是本程序进程开启的Logcat收集进程那么两者的USER一致)
     * 如果不关闭会有多个进程读取logcat日志缓存信息写入日志文件
     * @param allProcList
     * @return
     */
    public void killLogcatProc(List<ProcessInfo> allProcList) {
        if (process != null) {
            process.destroy();
        }
        String packName = this.mContext.getPackageName();
        String myUser = LogUtil.getAppUser(packName, allProcList);
        for (ProcessInfo processInfo : allProcList) {
            if (processInfo.name.toLowerCase().equals("logcat")
                    && processInfo.user.equals(myUser)) {
                android.os.Process.killProcess(Integer
                        .parseInt(processInfo.pid));
                // recordLogServiceLog("kill another logcat process success,the process info is:"
                // + processInfo);
            }
        }
    }
}
